import { Controller, Post, Body, HttpCode, HttpStatus, Logger } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiBody } from '@nestjs/swagger';
import { AuthService } from './auth.service';
import { LoginDto } from './dto/login.dto';
import { ApiResponse as ApiResponseDto } from '../common/dto/response.dto';

@ApiTags('认证')
@Controller('auth')
export class AuthController {
  private readonly logger = new Logger(AuthController.name);

  constructor(private readonly authService: AuthService) {}

  @Post('login')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({
    summary: '用户登录',
    description: '用户登录获取访问令牌'
  })
  @ApiBody({
    type: LoginDto,
    description: '登录信息'
  })
  @ApiResponse({
    status: 200,
    description: '登录成功',
    schema: {
      example: {
        code: 200,
        message: '登录成功',
        data: {
          access_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
          user: {
            id: 1,
            username: 'admin',
            email: 'admin@yuheng.com',
            nickname: '系统管理员',
            role: 'admin',
            isActive: true,
            lastLoginAt: '2025-08-15T10:00:00.000Z'
          }
        },
        timestamp: '2025-08-15T10:00:00.000Z'
      }
    }
  })
  @ApiResponse({
    status: 401,
    description: '用户名或密码错误',
    schema: {
      example: {
        code: 401,
        message: '用户名或密码错误',
        timestamp: '2025-08-15T10:00:00.000Z'
      }
    }
  })
  async login(@Body() loginDto: LoginDto) {
    this.logger.log(`收到登录请求 - 用户名: ${loginDto.username}, 密码长度: ${loginDto.password.length}`);
    this.logger.log(`完整请求体: ${JSON.stringify(loginDto)}`);
    
    try {
      const result = await this.authService.login(loginDto);
      this.logger.log(`登录成功 - 用户名: ${loginDto.username}, 用户ID: ${result.user.id}`);
      
      return ApiResponseDto.success(result, '登录成功');
    } catch (error) {
      this.logger.error(`登录失败 - 用户名: ${loginDto.username}, 错误: ${error.message}`);
      throw error;
    }
  }
}
